package com.chris.springdemo.controller;

import com.chris.springdemo.entity.AlipayInfoEntity;
import com.chris.springdemo.service.TestService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.request.async.DeferredResult;

import java.time.LocalDateTime;
import java.util.List;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

/**
 * @author wujf
 * @date 2021/10/15
 */
@RestController
public class TestController {

    @Autowired
    private TestService testService;

    @GetMapping("/list")
    public List<AlipayInfoEntity> query() {
        return testService.listInfo();
    }

    @GetMapping("/test1")
    public String test1() {
        // 创建 ScheduledThreadPool 线程池
        ScheduledExecutorService threadPool = Executors.newScheduledThreadPool(10);
        System.out.println("scheduleAtFixedRate 方法添加任务：" + LocalDateTime.now());
        threadPool.scheduleAtFixedRate(() -> {
                    System.out.println("执行 scheduleAtFixedRate 方法：" + LocalDateTime.now());
                    // 休眠 2s
                    try {
                        TimeUnit.SECONDS.sleep(2);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                },
                0L, // 3s 后开始执行定时任务
                2L, // 定时任务的执行间隔为 2s
                TimeUnit.SECONDS); // 描述上面两个参数的时间单位
        return "success";
    }


    @GetMapping("/test2")
    public DeferredResult<String> test2() throws InterruptedException {
        DeferredResult<String> deferredResult = new DeferredResult<>(5000L);
        // Thread.sleep(6000L);


        deferredResult.onTimeout(() -> {
            System.out.println("超时了");
        });

        deferredResult.onError((e) -> {
            e.printStackTrace();
            System.out.println("错误了...");
        });
        // 返回一个DeferredResult
        // deferredResult.setResult("success");
        return deferredResult;
    }

}
